import { useMemberStore } from '@/stores'

// 地址
const baseURL = 'http://localhost:88/'

// 添加请求拦截
const httpRequest = {
  // 拦截前触发
  invoke(options: UniApp.RequestOptions) {
    // 1. 非http开头需要拼接地址
    if(!options.url.startsWith('http')){
      options.url = baseURL + options.url
    }
    // 请求超时
    options.timeout = 10000
    // 添加请求头
    options.header = {
      ...options.header,
      'source-client':'miniapp',
    }
    const useMember = useMemberStore()
    const token = useMember.profile?.token
    if(token){
      options.header.Authorization = token
    }
  }
}

// 注册
uni.addInterceptor('request', httpRequest)

// 响应拦截
interface Data<T> {
  code: number
  msg: string
  data: T
}
const httpRsponse = <T>(options: UniApp.RequestOptions) =>{
  // 返回 Promise 对象
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      // 请求成功
      success(res){
        const response = res.data as Data<T>
        if(response.code === 0) {
          resolve(response)
        }else if(response.code === 401){
          // 清理token
          const useMember = useMemberStore()
          useMember.clearProfile()
          // 跳转登录页
          // uni.navigateTo({ url: '/pages/login/login' })
          reject(res)
        }else{
          uni.showToast({
            title: (res.data as Data<T>).msg || '请求错误',
            icon: 'none',
          })
          reject(res)
        }
      },
      // 失败
      fail(err){
        uni.showToast({
          title:'网络错误,换个网络试试',
          icon: 'none',
        })
        reject(err)
      }
    })
  })
}

export default httpRsponse